package com.zhiyun.service.impl;

import com.zhiyun.domain.Admin;
import com.zhiyun.mapper.AdminMapper;
import com.zhiyun.service.AdminService;
import com.zhiyun.util.Db;
import com.zhiyun.vo.Result;

import java.util.List;

/**
 * @author zc
 * @Date 2025/4/29 上午9:00
 */
public class AdminServiceImpl implements AdminService {
    AdminMapper adminMapper = Db.getMapper(AdminMapper.class);
    @Override
    public Result adminLogin(Admin admin) {
        Admin oldAdmin = adminMapper.selectByUserName(admin.getUsername());
        if (oldAdmin == null){
            return Result.fail("登录失败");
        }else {
            if (!oldAdmin.getPassword().equals(admin.getPassword())){
                return Result.fail("密码错误");
            }else {
                return Result.ok("登录成功",oldAdmin);
            }
        }
    }


    @Override
    public Result selectAll() {
        List<Admin> list =  adminMapper.selectAll();
        return Result.ok(list);
    }

    @Override
    public Result insertAdmin(Admin admin) {
        Admin oldAdmin = adminMapper.selectByUserName(admin.getUsername());
        if (oldAdmin != null){
            return Result.fail("管理员已经存在");
        }
        int rows = adminMapper.insert(admin);
        if (rows > 0){
            return Result.okMsg("添加成功");
        }
        return Result.fail("添加失败");
    }

    @Override
    public Result updateAdmin(Admin admin) {
        Admin oldAdmin = adminMapper.selectByPrimaryKey(admin.getId());
        if (oldAdmin == null){
            return Result.fail("要修改的管理员不存在");
        }
        if (!oldAdmin.getUsername().equals(admin.getUsername())){
            Admin admin1 = adminMapper.selectByUserName(admin.getUsername());
            if (admin1 != null){
                return Result.fail("管理员用户名已存在");
            }
        }
        int rows = adminMapper.updateByPrimaryKey(admin);
        if (rows > 0){
            return Result.okMsg("修改成功");
        }
        return Result.fail("修改失败");
    }

    @Override
    public Result deleteAdmin(Admin admin) {
        Admin oldAdmin = adminMapper.selectByPrimaryKey(admin.getId());
        if (oldAdmin == null){
            return Result.fail("该管理员不存在");
        }
        int rows = adminMapper.deleteByPrimaryKey(admin.getId());
        if (rows > 0){
            return Result.okMsg("删除成功");
        }
        return Result.fail("删除失败");
    }

    @Override
    public Result selectAdminById(Integer id) {
        return Result.ok(adminMapper.selectByPrimaryKey(id));
    }
}
